<template>
  <div class="page">
    <div class="page-container">
			<Header activeId="7" />
			<div class="content">
        <Bread :data="[{text: '首页', href: '/'}, {text: '在线服务', href: '/service'}, {text: '在线预约'}]" />
        <div class="paner">
          <div class="paner-body">
            <b-form class="paner-form">
              <b-row class="justify-content-md-start">
                <b-col xs="12" sm="12" lg="12">
                  <div class="form-groups">
                    <label class="form-groups-label">日期：</label>
                    <div class="form-groups-content">
                      <b-form-datepicker v-model="form.date" :state="valid.date" placeholder="请选择日期"></b-form-datepicker>
                      <b-form-invalid-feedback :state="valid.date">{{ message.date }}</b-form-invalid-feedback>
                    </div>
                  </div>
                </b-col>
                <b-col xs="12" sm="12" lg="12">
                  <div class="form-groups">
                    <label class="form-groups-label">人数：</label>
                    <div class="form-groups-content">
                      <b-form-input
                        v-model="form.persons"
                        :state="valid.persons"
                        type="number"
                        placeholder="请输入人数"
                        required
                      ></b-form-input>
                      <b-form-invalid-feedback :state="valid.persons">{{ message.persons }}</b-form-invalid-feedback>
                    </div>
                  </div>
                </b-col>
                <b-col xs="12" sm="12" lg="12">
                  <div class="form-groups">
                    <label class="form-groups-label">身份证号：</label>
                    <div class="form-groups-content">
                      <b-form-input
                        v-model="form.idcards"
                        :state="valid.idcards"
                        type="text"
                        placeholder="请输入身份证号"
                        required
                      ></b-form-input>
                      <b-form-invalid-feedback :state="valid.idcards">{{ message.idcards }}</b-form-invalid-feedback>
                    </div>
                  </div>
                </b-col>
                <b-col xs="12" sm="12" lg="12">
                  <div class="form-groups">
                    <label class="form-groups-label">手机号码：</label>
                    <div class="form-groups-content">
                      <b-form-input
                        v-model="form.phonenumber"
                        :state="valid.phonenumber"
                        type="text"
                        placeholder="请输入手机号码"
                        required
                      ></b-form-input>
                      <b-form-invalid-feedback :state="valid.phonenumber">{{ message.phonenumber }}</b-form-invalid-feedback>
                    </div>
                  </div>
                </b-col>
                <b-col xs="12" sm="12" lg="12">
                  <div class="form-groups">
                    <label class="form-groups-label">验证码：</label>
                    <div class="form-groups-content" style="display:flex">
                      <div style="width:130px;">
                        <b-form-input
                          v-model="form.code"
                          :state="valid.code"
                          type="text"
                          placeholder="请输入验证码"
                          required
                        ></b-form-input>
                        <b-form-invalid-feedback :state="valid.code">{{ message.code }}</b-form-invalid-feedback>
                      </div>
                      <div style="padding-left:8px;width:80px;">
                        <img v-if="codeUrl" @click="recode" :src="codeUrl" height="38px" class="form-code-image" />
                      </div>
                    </div>
                  </div>
                </b-col>
                <b-col xs="12" sm="12" lg="12">
                  <div class="form-groups">
                    <label class="form-groups-label"></label>
                    <div class="form-groups-content">
                      <b-button @click="handleSubmit" variant="primary">提交</b-button>
                      <a href="/service" class="btn btn-outline-primary">返回</a>
                    </div>
                  </div>
                </b-col>
              </b-row>
            </b-form>
          </div>
        </div>
			</div>
      <Footer />
		</div>
	</div>
</template>

<script>
import Header from '@/components/header.vue'
import Footer from '@/components/footer.vue'
import Bread from '@/components/bread.vue'

export default {
	components: {
    Header,
    Footer,
    Bread
	},

  data () {
    return {
      form: {
        date: '',
        persons: '',
        idcards: '',
        phonenumber: '',
        code: ''
      },
      code: '',
      codeUrl: '',
      rules: {
        date: [
          { required: true, message: '请选择日期' }
        ],
        persons: [
          { required: true, message: '请输入人数' },
          {
            validator (rule, value, callback) {
              if (value === '') {
                callback(new Error('请输入人数'))
              } else if (!/^\d+$/.test(value)) {
                callback(new Error('请输入数字!'))
              } else {
                callback()
              }
            },
            message: '请输入数字'
          }
        ],
        idcards: [
          { required: true, message: '请输入身份证号' },
          { regexp: /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[\dX]$/, message: '请输入身份证号' }
        ],
        phonenumber: [
          { required: true, message: '请输入手机号码' },
          { regexp: /^0{0,1}(13[0-9]|15[3-9]|15[0-2]|18[0-9])[0-9]{8}$/, message: '请输入手机号' }
        ],
        code: [
          { required: true, message: '请输入验证码' }
        ]
      },
      valid: {
        date: null,
        persons: null,
        idcards: null,
        phonenumber: null,
        code: null
      },
      message: {
        date: '',
        persons: '',
        idcards: '',
        phonenumber: '',
        code: ''
      }
    }
  },

  mounted () {
    this.recode()
  },

  methods: {
    recode () {
      // 生成指定长度的随机字符串
      function generateRandomCode(length) {
        let code = '';
        const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        const charactersLength = characters.length;
        for (let i = 0; i < length; i++) {
          code += characters.charAt(Math.floor(Math.random() * charactersLength));
        }
        return code;
      }
      
      // 在Canvas上绘制验证码图片
      function drawCaptcha(canvas, code) {
        const ctx = canvas.getContext('2d');
        
        // 设置画布尺寸
        canvas.width = 200;
        canvas.height = 100;
        
        // 绘制背景
        ctx.fillStyle = 'lightgray';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        
        // 绘制验证码文本
        ctx.font = '48px Arial';
        ctx.fillStyle = 'black';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(code, canvas.width / 2, canvas.height / 2);
        
        // 绘制干扰线
        for (let i = 0; i < 10; i++) {
          ctx.strokeStyle = randomColor();
          ctx.beginPath();
          ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
          ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
          ctx.stroke();
        }
      }
      
      // 生成随机的RGB颜色
      function randomColor() {
        const r = Math.floor(Math.random() * 256);
        const g = Math.floor(Math.random() * 256);
        const b = Math.floor(Math.random() * 256);
        return `rgb(${r},${g},${b})`;
      }

      // 使用例子
      const canvas = document.createElement('canvas');
      const code = generateRandomCode(4);
      this.code = code
      drawCaptcha(canvas, code);

      // 将Canvas添加到页面上展示
      this.codeUrl = canvas.toDataURL('image/png')
    },
    // 提交
    handleSubmit () {
      let res = this.checkValid()
      this.validated = true
      if (!res) {
        return true
      }
      this.submit()
    },
    // 发送数据
    submit () {
      this.$axios.post(this.form).then(res => {

      })
    },
    // 验证
    checkValid () {
      let result = false
      let keys = Object.keys(this.form)
      keys.forEach(key => {
        let value = this.isValid(key)
        this.valid[key] = value.valid
        this.message[key] = value.message
        result = result || value
      })
      return result
    },
    // 是否验证通过
    isValid (name) {
      let value = this.form[name]
      let rules = this.rules[name] || []
      let valid = true, message
      rules.forEach(item => {
        // 必需
        if (item.required) {
          if (!value) {
            valid = false
            message = item.message
          }
        }
        // 正则
        else if (Object.prototype.toString.call(item.regexp) === '[object RegExp]') {
          valid = item.regexp.test(value)
          if (!valid) {
            message = item.message
          }
        }
        // 自定义
        else if (typeof item.validator === 'function') {
          item.validator.call(this, item, value, function(res){
            if (res instanceof Error) {
              valid = false
              message = res.message || item.message
            }
          })
        }
      })
      return {
        valid, message
      }
    },
  }
}
</script>

<style lang="less" scoped>
.paner {
  margin-bottom: 8px;
  padding-top: 16px;
  padding-bottom: 16px;
  .paner-form {
    flex: 1;
  }
  .form-groups {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    .form-groups-label {
      margin-bottom: 0;
      width: 100px;
      text-align: right;
    }
    .form-groups-content {
      flex: 1;
    }
  }
  .form-code-image {
    cursor: pointer;
  }
}
</style>
